package com.chen.sample1.web.config;

import com.chen.sample1.common.constant.AliErrorCodeEnum;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.*;

/**
 * @desc Knife4j+Swagger 配置文件
 * @Author Chentian
 * @date 2021/9/1
 */
@Configuration
@EnableWebMvc
@EnableKnife4j
public class SwaggerConfig {
    /**
     * 创建文档
     */
    @Bean
    public Docket createRestApi(Environment environment) {
        //要开启的环境
        Profiles profiles = Profiles.of("dev", "test");
        boolean bEnable = environment.acceptsProfiles(profiles);

        Set<String> produces = new HashSet<>();
        produces.add("application/json");

        List<Response> responseMessageList = new ArrayList<>();
        Arrays.stream(AliErrorCodeEnum.values()).forEach(errorEnums -> responseMessageList.add(
                new Response(String.valueOf(errorEnums.getCode()),
                        errorEnums.getDescription(), false,
                        new ArrayList<>(), new ArrayList<>(), new ArrayList<>(),
                        new ArrayList<>())
                )
        );

        return new Docket(DocumentationType.OAS_30)
                .globalResponses(HttpMethod.GET, responseMessageList)
                .globalResponses(HttpMethod.POST, responseMessageList)
                .globalResponses(HttpMethod.DELETE, responseMessageList)
                .apiInfo(apiInfo())
                .groupName("web端接口")
                .produces(produces)
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.chen"))
                .paths(PathSelectors.any())
                .build().enable(bEnable);

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("xxx项目接口文档")
                //创建人
                .contact(new Contact("xxx", "", "xxx@cnicg.cn"))
                //版本号
                .version("1.0")
                //描述
                .description("该模块只为给大家提供以一个快速开发联调的环境")
                .build();
    }
}
